package com.gaeig.base;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;

public class ApplicationPersistenceManager {
  private static final PersistenceManagerFactory persistenceManagerFactory = JDOHelper.getPersistenceManagerFactory("transactions-optional");

  private static ThreadLocal<PersistenceManager> persistenceManagerThreadLocal = new ThreadLocal<PersistenceManager>();

  public static PersistenceManager getCurrentPersistenceManager() {
    if (persistenceManagerThreadLocal.get() == null) {
      persistenceManagerThreadLocal.set(getNewPersistenceManager());
    }
    return persistenceManagerThreadLocal.get();
  }

  public static void closeCurrentPersistenceManager() {
    PersistenceManager persistenceManager = getCurrentPersistenceManager();
    if (persistenceManager != null) {
      persistenceManager.close();
      persistenceManagerThreadLocal.set(null);
    }
  }

  public static Transaction getCurrentTransaction() {
    return getCurrentPersistenceManager().currentTransaction();
  }

  private static PersistenceManager getNewPersistenceManager() {
    return persistenceManagerFactory.getPersistenceManager();
  }
}
